//
//  YAYIPerformanceLineChart.m
//  YAYIDoctor
//
//  Created by Veer on 16/5/10.
//  Copyright © 2016年 hxp. All rights reserved.
//

#import "YAYIOALineChart.h"

#import "KAChartModel.h"
#import "UIBezierPath+BesselCurve.h"
#import "XDottedLineView.h"
#import "VRCalendarTool.h"

#define bottomMargin 34.0
#define topMargin 4
#define leftMargin 10
// 最大y值的 y左边点
#define MaxYY 4
#define MaxXX (kScreenWidth - 10)

#define pointGrayColor RGB(170, 170, 170)
#define XYAxisColor RGB(224, 224, 224)
#define LineColor RGB(138, 138, 138)



@interface YAYIOALineChart(){
    CGPoint startPoint;
}



@property (nonatomic, weak) UIView *yValueContainerView;

@property (nonatomic, weak) CAShapeLayer *lineShapeLayer;
@property (nonatomic, weak) CALayer *shadowLayer;
@property (nonatomic, weak) CALayer *containerLayer;

@property (nonatomic, weak) UILabel *xLbl1;
@property (nonatomic, weak) UILabel *xLbl2;


@property (nonatomic, weak) XDottedLineView *lineView;

/** 原点位置 */
@property (nonatomic, strong) const NSMutableArray *pointArray;
/** 原点位置 */
@property (nonatomic, assign) const CGPoint originPoint;
/** x轴最大刻度 */
@property (nonatomic, assign) const NSInteger maxX;


@end


@implementation YAYIOALineChart

@synthesize dataArray = _dataArray;


/**
 * 设置模型，并且模型转换成点坐标
 */
- (void)setDataArray:(NSMutableArray *)dataArray
{
    _dataArray = dataArray;
    
    // 先清空以前视图
    [self clearSubView];
    
    // 画出y轴的值
//    if (dataArray.count > 0) {
    
    CGFloat maxY = 0.0;
    CGFloat sum = 0.0;
    for (KAChartModel *model in dataArray) {
        
        sum += model.money;
        if (model.money > maxY) {
            maxY = model.money;
        }
    }

    // 计算平均值
    CGFloat average = sum / self.maxX;
    CGFloat averageY = self.originPoint.y - average / maxY * (self.originPoint.y - MaxYY);
    if (averageY > 0) {
        [self createAverageLineWithY:averageY];
    }

    
    // 算出每一小格的像素长度
    CGFloat scaleX = (self.width - 2 * leftMargin) / (self.maxX - 1);
    
    // 添加默认点，x轴上
    NSMutableArray *pointArray = [NSMutableArray array];
    for (int i = 0; i < self.maxX; i++) {
        
        [pointArray addObject:[NSValue valueWithCGPoint:CGPointMake(i * scaleX + self.originPoint.x, self.originPoint.y)]];
    }
    
    NSDate *firstDate = [VRCalendarTool dateForFistDayOnWeek:[NSDate date]];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd";
    
    //    NSDate *lastDate = [VRCalendarTool dateForLastDayOnWeek:[NSDate date]];
    //    NSString *firstDateStr = [VRCalendarTool stringWithDate:firstDate formatString:@"MM-dd"];
    for (int i = 0; i < dataArray.count; i++) {
        
        KAChartModel *model = dataArray[i];
        double money = model.money;
        
        NSInteger curTime = [[model.time substringFromIndex:model.time.length - 2] integerValue];
//        if (curTime > self.maxX) {
//            continue;
//        }
        
        NSInteger scaleCount = curTime - 1;
        if (self.chartType == ChartTypeThisWeek) {
            NSDate *firstAccountDate = [formatter dateFromString:model.time];
            NSInteger timeStamp = [firstAccountDate timeIntervalSinceDate:firstDate];
            scaleCount = timeStamp / (24  * 60 * 60);
        }
        
        // 每一小格 * 格数 + 左边距离 就是x值了
        CGFloat ponintX = scaleX * scaleCount + self.originPoint.x;
        CGFloat ponintY = self.originPoint.y - money / maxY * (self.originPoint.y - MaxYY);
        
        // 保存点坐标
        CGPoint point = CGPointMake(ponintX, ponintY);
        pointArray[scaleCount] = [NSValue valueWithCGPoint:point];
    }
    self.pointArray = pointArray;
    
    [self createBezierPathWithPointArray:pointArray];
//    }else{
//
//        self.pointArray = [NSMutableArray array];
//        [self setupYAxisLabelWithMaxY:100000 incrementNum:100000];
//    }
    
    
    [self setNeedsDisplay];
}


- (void)setChartType:(ChartType)chartType
{
    
    _chartType = chartType;
    
    // 计算最大x轴刻度
    if (ChartTypeThisMonth == chartType) { // 本月
        self.maxX = [self getNumberOfDaysInMonth];
    }else if (ChartTypeThisYear == chartType){ // 今年
        self.maxX = 12;
    }else{ // 本周
        self.maxX = 7;
    }
    
    // 画底部label
    CGFloat startY = self.height - bottomMargin;
    
    UILabel *xLbl1 = [[UILabel alloc] init];
    xLbl1.font = VRFont(12);
    xLbl1.textColor = RGB(145, 149, 154);
    xLbl1.text = self.xArray[0];
    [self addSubview:xLbl1];
    [xLbl1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(startY + 8);
        make.centerX.mas_equalTo(self.mas_left).offset(self.originPoint.x);
        make.height.mas_equalTo(20);
    }];
    
    UILabel *xLbl2 = [[UILabel alloc] init];
    xLbl2.font = VRFont(12);
    xLbl2.textColor = RGB(145, 149, 154);
    xLbl2.text = [self.xArray lastObject];
    [self addSubview:xLbl2];
    [xLbl2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(startY + 8);
        make.centerX.mas_equalTo(self.mas_left).offset(MaxXX);
        make.height.mas_equalTo(20);
    }];
}


- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        
        
        self.backgroundColor = [UIColor whiteColor];
        
//        self.dataArray = [NSMutableArray array];
        
        // 算出原点位置
        self.originPoint = CGPointMake(leftMargin, frame.size.height - bottomMargin);
        
        UIView *yValueContainerView = [[UIView alloc] init];
        yValueContainerView.frame = CGRectMake(0, 0, self.originPoint.x, frame.size.height);
        [self addSubview:yValueContainerView];
        self.yValueContainerView = yValueContainerView;
//        self.backgroundColor = [UIColor yellowColor];
        
        CALayer *containerLayer = [CALayer layer];
        containerLayer.frame = self.bounds;
        [self.layer addSublayer:containerLayer];
        self.containerLayer = containerLayer;
        
        

//        UILabel *tipLbl = [[UILabel alloc] init];
//        tipLbl.text = @"长按滑动显示金额";
//        tipLbl.textAlignment = NSTextAlignmentCenter;
//        tipLbl.font = VRFont(16);
//        tipLbl.textColor = RGBAlpha(0xaa, 0xaa, 0xaa, 0.4);
//        [self addSubview:tipLbl];
//        [tipLbl mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.centerX.mas_equalTo(self);
//            make.bottom.mas_equalTo(0);
//        }];
        
        
        // 位移点
//        YAYILineView *lineView = [[YAYILineView alloc] init];
//        lineView.lineColor = RGB(0xaa, 0xaa, 0xaa);
//        lineView.lineDirect = LineDirectV;
//        lineView.hidden = YES;
//        lineView.frame = CGRectMake(0, 0, 0.5, frame.size.height - bottomMargin);
//        [self addSubview:lineView];
//        self.lineView = lineView;
//
//        UILongPressGestureRecognizer *longGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPressed:)];
//        [self addGestureRecognizer:longGesture];
    }
    return self;
}


- (void)drawRect:(CGRect)rect
{
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    
    // 画x，y轴
    [XYAxisColor set];
    CGContextSetLineWidth(ctx, 1);
    
    CGContextMoveToPoint(ctx, leftMargin, self.height - bottomMargin);
    CGContextAddLineToPoint(ctx, self.width - leftMargin, self.height - bottomMargin);
    
    CGContextMoveToPoint(ctx, leftMargin, topMargin);
    CGContextAddLineToPoint(ctx, self.width - leftMargin, topMargin);
    
//    CGContextFillPath(ctx);
    CGContextStrokePath(ctx);
    

    UILabel *xLbl1 = [[UILabel alloc] init];
    xLbl1.font = VRFont(12);
    xLbl1.textColor = RGB(145, 149, 154);
    xLbl1.text = self.xArray[0];
    [self addSubview:xLbl1];
    [xLbl1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.originPoint.y + 4);
        make.left.mas_equalTo(self.mas_left).offset(self.originPoint.x - 2);
        make.height.mas_equalTo(20);
    }];
    
    UILabel *xLbl2 = [[UILabel alloc] init];
    xLbl2.font = VRFont(12);
    xLbl2.textColor = RGB(145, 149, 154);
    xLbl2.text = [self.xArray lastObject];
    [self addSubview:xLbl2];
    [xLbl2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.originPoint.y + 4);
        make.right.mas_equalTo(self.mas_left).offset(MaxXX + 2);
        make.height.mas_equalTo(20);
    }];
}



- (void)setupYAxisLabelWithMaxY:(CGFloat)maxY incrementNum:(CGFloat)incrementNum
{
    
    CGFloat incrementNumTemp = incrementNum / 100.0;
    
    // 小数位数
    NSInteger decimalDigits = 0;
    NSString *tailStr = @"";
    if (incrementNumTemp >= 1000 && incrementNumTemp < 10000) {
        incrementNumTemp = incrementNumTemp / 1000;
        tailStr = @"K";
    }else if (incrementNumTemp >= 10000) {
        tailStr = @"W";
        incrementNumTemp = incrementNumTemp / 10000;
    }else{
        
        if (incrementNumTemp < 1 && incrementNumTemp >= 0.1) {
            decimalDigits = 1;
        }else if (incrementNumTemp < 0.1 && incrementNumTemp >= 0.01){
            decimalDigits = 2;
        }else if(incrementNumTemp < 0.01){
            decimalDigits = 2;
            incrementNum = maxY;
            incrementNumTemp = incrementNum / 100.0;
        }
    }
    
    int yLblCount = (int)(maxY / incrementNum);
    CGFloat margin = (self.originPoint.y - MaxYY) / yLblCount;
    
    for (int i = 0; i < yLblCount; i++) {
        
        UILabel *lbl = [[UILabel alloc] init];
        
        if (decimalDigits == 0) {
            lbl.text = [NSString stringWithFormat:@"%.0f %@", ((yLblCount - i) * incrementNumTemp), tailStr];
        }else if (decimalDigits == 1){
            lbl.text = [NSString stringWithFormat:@"%.1f %@", ((yLblCount - i) * incrementNumTemp), tailStr];
        }else if (decimalDigits == 2){
            lbl.text = [NSString stringWithFormat:@"%.2f %@", ((yLblCount - i) * incrementNumTemp), tailStr];
        }
        
        lbl.font = VRFont(10);
        lbl.textAlignment = NSTextAlignmentRight;
        lbl.textColor = RGB(158, 170, 193);
        lbl.x = 0;
        lbl.width = 40 - 4;
        lbl.height = 20;
        lbl.centerY = MaxYY + i * margin;
        [self.yValueContainerView addSubview:lbl];
    }
}

- (void)createAverageLineWithY:(CGFloat)averageY
{
    XDottedLineView *lineView = [[XDottedLineView alloc] init];
    lineView.lineColor = LineColor;
    lineView.frame = CGRectMake(self.originPoint.x, averageY, self.width - leftMargin * 2, 1);
    [self addSubview:lineView];
}

/**
 绘制贝塞尔曲线方法

 @param pointArray 点数组
 */
- (void)createBezierPathWithPointArray:(NSMutableArray *)pointArray
{
    
    NSMutableArray *pointArrayTemp = [NSMutableArray arrayWithArray:pointArray];
    
    CGPoint firstPoint = [[pointArray firstObject] CGPointValue];
    
    UIBezierPath *curve = [UIBezierPath bezierPath];
    
    [curve moveToPoint:firstPoint];
    for (int i = 0; i < pointArray.count; i++) {
        
        CGPoint point = [pointArray[i] CGPointValue];
        [curve addLineToPoint:point];
        [curve moveToPoint:point];
    }
    
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.strokeColor = RGB(51, 51, 51).CGColor;
    shapeLayer.fillColor = [UIColor clearColor].CGColor;
    shapeLayer.lineWidth = 1.0;
    shapeLayer.path = curve.CGPath;
    shapeLayer.lineCap = kCALineCapRound;
//    shapeLayer.hidden = YES;
    [self.containerLayer addSublayer:shapeLayer];
    self.lineShapeLayer = shapeLayer;
    
    // 折线展示动画
//    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
//    animation.duration = 2.5f;
//    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
//    animation.fromValue = @(0.0);
//    animation.toValue = @(1.0);
//    [shapeLayer addAnimation:animation forKey:@"path"];
    
    
    
//    UIBezierPath *curveCopy = [curve copy];
//    [curveCopy moveToPoint:lastPoint];
//    [curveCopy addLineToPoint:CGPointMake(lastPoint.x, self.originPoint.y)];
////    [curveCopy addLineToPoint:CGPointMake(firstPoint.x, self.originPoint.y)];
//    [curveCopy addLineToPoint:self.originPoint];
//    [curveCopy addLineToPoint:firstPoint];
//
//    //遮罩图层
//    CAShapeLayer *shadeLayer2 = [CAShapeLayer layer];
//    shadeLayer2.path = curveCopy.CGPath;
//    shadeLayer2.fillColor = [UIColor greenColor].CGColor;
//    //渐变图层
//    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
//    gradientLayer.anchorPoint = CGPointMake(0, 0);
//    gradientLayer.frame = CGRectMake(firstPoint.x, 0, lastPoint.x - firstPoint.x, self.height);
//    gradientLayer.startPoint = CGPointMake(0, 0);
//    gradientLayer.endPoint = CGPointMake(0, 1);
//    gradientLayer.colors = @[(__bridge id)RGBA(57, 183, 252, 0.3).CGColor, (__bridge id)RGBA(255, 255, 255, 0.0).CGColor];
//    gradientLayer.locations = @[@(0.5f)];
//
//    CALayer *baseLayer = [CALayer layer];
//    baseLayer.frame = self.bounds;
//    [baseLayer addSublayer:gradientLayer];
//    [baseLayer setMask:shadeLayer2];
//    [self.containerLayer addSublayer:baseLayer];
//    self.shadowLayer = baseLayer;
    
    
    
//    [self drawPoint:firstPoint];
    for (NSValue *point in pointArray) {
        
        [self drawPoint:[point CGPointValue]];
    }
}


- (void)showLineByAnimation
{
    
    // 动画显示金额
    self.lineShapeLayer.hidden = NO;
    
    // 折现展示动画
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
    animation.duration = 2.0f;
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
    animation.fromValue = @(0.0);
    animation.toValue = @(1.0);
    [self.lineShapeLayer addAnimation:animation forKey:@"path"];
}




- (void)drawPoint:(CGPoint)point {
    
    CALayer * pointLayer = [CALayer layer];
    pointLayer.bounds = CGRectMake(0, 0, 6, 6);
    pointLayer.cornerRadius = 3;
    pointLayer.position = point;
    pointLayer.backgroundColor = point.y == self.originPoint.y ? [UIColor whiteColor].CGColor : MAINColor.CGColor;
    pointLayer.opaque = YES;
    pointLayer.borderColor = RGB(51, 51, 51).CGColor;
    pointLayer.borderWidth = 0.5;
    [self.containerLayer addSublayer:pointLayer];
    
    
//    CALayer * pointLayer2 = [CALayer layer];
//    pointLayer2.bounds = CGRectMake(0, 0, 6, 6);
//    pointLayer2.cornerRadius = 3;
//    pointLayer2.position = point;
//    pointLayer2.backgroundColor = LineColor.CGColor;
//    pointLayer2.opaque = YES;
//    [self.containerLayer addSublayer:pointLayer2];
}


#pragma mark - 点击事件
- (void)handleLongPressed:(UILongPressGestureRecognizer *)sender
{
    
    if (sender.state == UIGestureRecognizerStateBegan)
    {
        
//        self.superview.userInteractionEnabled = NO;
        self.lineView.hidden = NO;
        
        startPoint = [sender locationInView:sender.view];
        self.lineView.centerX = startPoint.x;
        
        if ([self.delegate respondsToSelector:@selector(OALineChartGuideLineDidShow)]) {
            
            [self.delegate OALineChartGuideLineDidShow];
        }
        [self getModelWithPointX:startPoint.x];
    }
    else if (sender.state == UIGestureRecognizerStateChanged)
    {
        
        
        CGPoint newPoint = [sender locationInView:sender.view];
        
        double newX = newPoint.x;
        if (newX < self.originPoint.x) {
            
            newX = self.originPoint.x;
        }else if (newX > MaxXX){
            
            newX = MaxXX;
        }
        
        self.lineView.centerX = newX;
        
        [self getModelWithPointX:newX];
    }
    else if (sender.state == UIGestureRecognizerStateEnded)
    {
        self.lineView.hidden = YES;
//        self.superview.userInteractionEnabled = YES;
        if ([self.delegate respondsToSelector:@selector(OALineChartGuideLineDidHide)]) {
            
            [self.delegate OALineChartGuideLineDidHide];
        }
    }
}


/**
 根据点来取出对应model

 @param pointX 点
 */
- (void)getModelWithPointX:(CGFloat)pointX
{
    
    CGFloat xScale  = (MaxXX - self.originPoint.x) / (self.maxX - 1);
    NSInteger index = (NSInteger)((pointX - self.originPoint.x + 4) / xScale);
    
    NSInteger curIndex = -1;
    for (int i = 0; i < self.pointArray.count; i++) {
        
        CGPoint point = [self.pointArray[i] CGPointValue];
        NSInteger curIndexTemp = (NSInteger)((point.x - self.originPoint.x + 4) / xScale);
        if (fabs(point.x - pointX) <= 4) {
            
            self.lineView.centerX = point.x;
            index = curIndexTemp;
            
            NSLog(@"index:%ld curIndexTemp:%ld", index, curIndexTemp);
        }
        
        if (index == curIndexTemp) {
            curIndex = i;
            break;
        }else if (index < curIndexTemp){
            break;
        }
    }
    
    NSLog(@"index:%ld curIndex:%ld", index, curIndex);
    
    if ([self.delegate respondsToSelector:@selector(OALineChartDidShowGuidelineWithModel:index:)]) {
        
        KAChartModel *model = nil;
        if (curIndex >= 0) {
            model = self.dataArray[curIndex];
        }
        [self.delegate OALineChartDidShowGuidelineWithModel:model index:index];
    }
}



#pragma mark - public
- (void)clearSubView
{
    
    // 清空左边y坐标值
    for (UIView *yValueLbl in self.yValueContainerView.subviews) {
        
        [yValueLbl removeFromSuperview];
    }
    
    // 清空字layer
    NSMutableArray *layerArray = [NSMutableArray arrayWithArray:self.containerLayer.sublayers];
    for (CALayer *layer in layerArray) {
        
        [layer removeFromSuperlayer];
    }
    
    for (UIView *subView in self.subviews) {
        [subView removeFromSuperview];
    }
}




#pragma mark - 工具方法
/** 通过时间获取时间戳 */
- (NSInteger)getTimeStampBy:(NSString *)timeStr
{
    NSDate *nowDate = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = [NSString stringWithFormat:@"YYYY-MM-dd %@", timeStr];
    NSString *dateStr = [dateFormatter stringFromDate:nowDate];
    
    dateFormatter.dateFormat = @"YYYY-MM-dd hh:mm";
    NSDate *lastDate = [dateFormatter dateFromString:dateStr];
    
    
    NSInteger timeStamp = [lastDate timeIntervalSince1970];
    return timeStamp;
}





/** 获取本月的天数 */
- (NSInteger)getNumberOfDaysInMonth
{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSRange range = [calendar rangeOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forDate:[NSDate date]];
    NSUInteger numberOfDaysInMonth = range.length;
    
    return numberOfDaysInMonth;
}

/** 获取本年的天数 */
- (NSInteger)getNumberOfDaysInYear
{
    NSUInteger days = 0;
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDate *today = [NSDate date];
    NSDateComponents *components = [calendar components:NSYearCalendarUnit fromDate:today];

    for (int i = 1; i <= 12; i++) {
        components.month = i;
        NSDate *month = [calendar dateFromComponents:components];
        days += [calendar rangeOfUnit:NSDayCalendarUnit
                               inUnit:NSMonthCalendarUnit
                              forDate:month].length;
    }
    
    return days;
}

/** 获取本月的开始时间戳 */
- (NSInteger)getStartStampInMonth
{
    NSDate *curDate = [NSDate date];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"YYYY-MM-01";
    NSString *dateStr = [formatter stringFromDate:curDate];
    
    formatter.dateFormat = @"YYYY-MM-dd";
    NSDate *startDate = [formatter dateFromString:dateStr];
    NSInteger startStamp = [startDate timeIntervalSince1970];
    
    return startStamp;
}


/** 获取本年的开始时间戳 */
- (NSInteger)getStartStampInYear
{
    NSDate *curDate = [NSDate date];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"YYYY-01-01";
    NSString *dateStr = [formatter stringFromDate:curDate];
    
    formatter.dateFormat = @"YYYY-MM-dd";
    NSDate *startDate = [formatter dateFromString:dateStr];
    NSInteger startStamp = [startDate timeIntervalSince1970];
    
    return startStamp;
}

/** 返回一个CGFloat数组， 第一个数 是 求出的y轴最大数 第二个数是增量*/
- (NSArray *)getMaxYWithMaxNumber:(CGFloat)number
{
    
    NSArray *numArray = @[@2, @3, @4, @5, @6, @8, @10];
    NSArray *incrementNumArray = @[@0.5, @0.5, @1, @1, @1, @2, @2];
    
    CGFloat divisor = 1;
    CGFloat highestDigis = number;
    while (highestDigis > 10) {
        
        highestDigis = highestDigis / 10;
        divisor *= 10;
    }
    
    int index = 0;
    for (int i = 0; i < numArray.count; i++) {
        
        CGFloat num = [numArray[i] floatValue];
        if (num >= highestDigis) {
            index = i;
            break;
        }
    }
    
    CGFloat incrementNum = [incrementNumArray[index] floatValue] * divisor;
    highestDigis = [numArray[index] floatValue] * divisor;
    
    NSLog(@"divisor:%f index:%d  highestDigis:%f", divisor, index, highestDigis);
    
    return @[@(highestDigis), @(incrementNum)];
}


#pragma mark - setter && getter
- (void)setXArray:(NSArray *)xArray
{
    _xArray = xArray;
    
    self.xLbl1.text = [xArray firstObject];
    self.xLbl2.text = [xArray lastObject];
}


@end
